package com.xc.file.web.controller;

import com.xc.core.enums.RedisPrefix;
import com.xc.file.config.Constants;
import com.xc.file.enums.FailCode;
import com.xc.file.model.DownloadModel;
import com.xc.file.service.DownloadService;
import com.xc.file.service.FileService;
import com.xc.tool.utils.FileUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * <p>下载文件接口</p>
 *
 * @author xc
 * @version v1.0.0
 */
@Api(tags = "下载文件接口")
@Controller
@Slf4j
public class DownloadFile {

    @Autowired
    private DownloadService downloadService;
    @Autowired
    private FileService fileService;
    @Autowired
    private Constants constants;

    @ApiOperation(value = "下载当前用户的文件",
            notes = "1，下载文件必须符合下载条件，在安全链接允许范围内可下载\n" +
                    "2，宽高和比例不能同时使用，同时存在使用比例")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "文件id", name = "fid", paramType = "path", required = true),
            @ApiImplicitParam(value = "用户token", name = "token", paramType = "query", required = true),
            @ApiImplicitParam(value = "open是否直接打开,0:可以直接打开，1:不能直接打开，默认下载", name = "open", paramType = "query"),
            @ApiImplicitParam(value = "压缩图片高", name = "w", paramType = "query"),
            @ApiImplicitParam(value = "压缩图片宽", name = "h", paramType = "query"),
            @ApiImplicitParam(value = "压缩比例,小数", name = "s", paramType = "query"),
    })
    @GetMapping("/user/{userId}/file/{fid}")
    public void downloadUserFile(@PathVariable String userId, @PathVariable String fid,
                                 @RequestParam(value = "open", required = false) Integer open,
                                 @RequestParam(value = "w", required = false) Integer w,
                                 @RequestParam(value = "h", required = false) Integer h,
                                 @RequestParam(value = "s", required = false) Double s,
                                 HttpServletRequest request, HttpServletResponse response) {
        //去除文件后缀
        fid = FileUtils.getNotSuffixFileName(fid);
        if (fid == null) {
            throw FailCode.FIXED_NOT_NULL.getOperateException();
        }
        DownloadModel downloadModel = fileService.getDownloadModel(userId, fid, RedisPrefix.USER_DOWNLOAD.getKey());
        downloadModel.setOpen(open != null ? open : 1);
        downloadModel.setRange(request.getHeader("range"));
        downloadService.downloadFile(response, downloadModel, w, h, s);
    }

    @ApiOperation(value = "根据fid下载文件",
            notes = "1，下载文件必须符合下载条件，在安全链接允许范围内可下载\n" +
                    "2，宽高和比例不能同时使用，同时存在使用比例")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "文件id", name = "fid", paramType = "path", required = true),
            @ApiImplicitParam(value = "共享", name = "shareId", paramType = "path", required = true),
            @ApiImplicitParam(value = "open是否直接打开,0:可以直接打开，1:不能直接打开，默认下载", name = "open", paramType = "query"),
            @ApiImplicitParam(value = "压缩图片高", name = "w", paramType = "query"),
            @ApiImplicitParam(value = "压缩图片宽", name = "h", paramType = "query"),
            @ApiImplicitParam(value = "压缩比例,小数", name = "s", paramType = "query"),
    })
    @GetMapping("/share/{visitCode}/file/{fid}")
    public void downloadShareFile(@PathVariable String visitCode, @PathVariable String fid,
                                  @RequestParam(value = "open", required = false) Integer open,
                                  @RequestParam(value = "w", required = false) Integer w,
                                  @RequestParam(value = "h", required = false) Integer h,
                                  @RequestParam(value = "s", required = false) Double s,
                                  HttpServletRequest request, HttpServletResponse response) {
        //去除文件后缀
        fid = FileUtils.getNotSuffixFileName(fid);
        if (fid == null) {
            throw FailCode.FIXED_NOT_NULL.getOperateException();
        }
        //验证文件
        DownloadModel downloadModel = fileService.getDownloadModel(visitCode, fid, RedisPrefix.SHARE_DOWNLOAD.getKey());
        downloadModel.setRange(request.getHeader("range"));
        downloadModel.setOpen(open != null ? open : 1);
        downloadService.downloadFile(response, downloadModel, w, h, s);
    }

    @ApiOperation(value = "根据fid下载文件",
            notes = "1，下载文件必须符合下载条件，在安全链接允许范围内可下载\n" +
                    "2，/**后面对应网盘的文件目录及文件名称")
    @ApiImplicitParams({
            @ApiImplicitParam(
                    value = "下载类型，download：默认下载，开放下载，cdn：cdn下载地址",
                    name = "downloadType", paramType = "path", required = true
            ),
            @ApiImplicitParam(value = "用户主键", name = "userId", paramType = "path", required = true),
            @ApiImplicitParam(value = "open是否直接打开,0:可以直接打开，1:不能直接打开，默认下载", name = "open", paramType = "query"),
    })
    @GetMapping("/open/{type}/{userId}/**")
    public void downloadOpenFile(@PathVariable String type, @PathVariable String userId,
                                 @RequestParam(required = false) Integer open,
                                 HttpServletRequest request, HttpServletResponse response) {
        String path;
        if (type.equals("cdn")) {
            path = constants.getOpenCndUrl() + userId;
        } else {
            path = constants.getOpenDownloadUrl() + userId;
        }
        String url = request.getRequestURI();
        try {
            url = URLDecoder.decode(url, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String filePath = url.substring(path.length());
        // 验证文件
        DownloadModel downloadModel = fileService.getOpenDownload(request.getHeader("referer"), userId, filePath);
        downloadModel.setOpen(open != null ? open : 1);
        downloadModel.setRange(request.getHeader("range"));
        downloadService.downloadFile(response, downloadModel, null, null, null);

    }
}
